import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

import 'model.dart';
import 'state.dart';

class ChatMessageListLogic extends GetxController {
  final ChatMessageListState state = ChatMessageListState();

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    EMClient.getInstance.chatManager.removeEventHandler(state.tag);
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    addChatListener();
  }

  /// 添加消息监听
  void addChatListener() {
    // 添加收消息监听
    EMClient.getInstance.chatManager.addEventHandler(
      state.tag,
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          for (EMMessage msg in messages) {
            receiveMessage(msg);
          }
        },
      ),
    );
  }

  /// 收到消息 处理
  receiveMessage(EMMessage msg) {
    int index = state.model.indexWhere(
        (element) => element.xinMsg?.conversationId == msg.conversationId);
    //找到了对应的会话
    if (index != -1) {
      state.model[index].xinMsg = msg;
      updateConversation(index);
    } else {
      getAppointConversation(msg);
    }
  }

  /// 更新会话
  updateConversation(int index) {
    // 先获取消息未读数
    state.model[index].superXin?.unreadCount().then((value) {
      state.model[index].serverMeg?.count = value;
      sortList();
    });
  }

  /// 获取会话,并更新列表
  getAppointConversation(EMMessage message) async {
    // 根据指定消息ID，获取当前会话
    EMConversation? conversation = await EMClient.getInstance.chatManager
        .getConversation('${message.conversationId}');
    // 获取当前会话消息未读数
    int? count = await conversation?.unreadCount();
    if (message.from == 'admin') {
      ChatModel model = ChatModel(
        serverMeg: ChatMessageEntity.fromJson({
          "nickName": "",
          "photoUrl": "",
          "detailsId": "",
          "owner": "",
          "index": 4,
          "age": 0
        }),
        superXin: conversation,
        xinMsg: message,
      )..serverMeg?.count = count;
      state.model.add(model);
    } else {
      final res = await Api.getInstance().getSessions('${conversation?.id}');
      if (res['code'] == 0 && res['data'] != null) {
        final data = res['data'];
        ChatModel model = ChatModel(
          serverMeg: ChatMessageEntity.fromJson(data),
          superXin: conversation,
          xinMsg: message,
        );
        model.serverMeg?.count = count;
        state.model.add(model);
      }
    }
    sortList();
  }

  onRefresh() async {
    state.model.clear();
    List<EMConversation> list =
        await EMClient.getInstance.chatManager.loadAllConversations();
    state.refreshController.refreshCompleted();
    for (EMConversation conversation in list) {
      // 获取当前会话的最新消息
      conversation.latestMessage().then((EMMessage? message) {
        //会话  最后一条消息
        if (message != null) {
          updateChatMessage(conversation: conversation, message: message);
        }
      });
    }
  }

  /// 获取用户信息
  updateChatMessage({
    EMMessage? message,
    EMConversation? conversation,
  }) async {
    /// 通过本地列表获取的会话
    conversation?.unreadCount().then((value) async {
      if (message?.from == 'admin') {
        ChatModel model = ChatModel(
          serverMeg: ChatMessageEntity.fromJson({
            "nickName": "",
            "photoUrl": "",
            "detailsId": "",
            "owner": "",
            "index": 4,
            "age": 0
          }),
          superXin: conversation,
          xinMsg: message,
        )..serverMeg?.count = value;
        state.model.add(model);
      } else {
        final res = await Api.getInstance().getSessions(conversation.id);
        if (res['code'] == 0 && res['data'] != null) {
          final data = res['data'];
          ChatModel model = ChatModel(
            serverMeg: ChatMessageEntity.fromJson(data),
            superXin: conversation,
            xinMsg: message,
          );
          model.serverMeg?.count = value;
          state.model.add(model);
        }
      }
      sortList();
    });
  }

  /// 排序
  sortList() {
    state.model.sort((a, b) {
      if (a.xinMsg?.from == 'admin' && b.xinMsg?.from != 'admin') {
        return -1; // admin 排在前面
      } else if (a.xinMsg?.from != 'admin' && b.xinMsg?.from == 'admin') {
        return 1; // admin 排在前面
      } else {
        int aaa = a.xinMsg?.serverTime ?? DateTime.now().microsecondsSinceEpoch;
        int bbb = b.xinMsg?.serverTime ?? DateTime.now().microsecondsSinceEpoch;
        return bbb.compareTo(aaa); // 其他按照时间排序
      }
    });
    state.model.refresh();
  }

  /// 根据不同的类型 返回最后一条消息内容
  String getContext({EMMessage? message}) {
    var body = message?.body;
    if (body?.type == MessageType.TXT) {
      var textBody = body as EMTextMessageBody;
      return textBody.content;
    }
    if (body?.type == MessageType.VOICE) {
      return '[语音消息]';
    }
    if (body?.type == MessageType.IMAGE) {
      return '[图片]';
    }
    if (body?.type == MessageType.VIDEO) {
      return '[视频]';
    }
    return "";
  }

  /// 时间
  String getServeTime(int index) {
    if (ObjectUtil.isEmpty(state.model[index].xinMsg?.serverTime)) {
      return "";
    }
    var time = int.parse('${state.model[index].xinMsg?.serverTime}');
    DateTime date = DateTime.fromMillisecondsSinceEpoch(time);
    return DateUtil.formatDate(date, format: DateFormats.h_m);
  }

  // 查找是否有相同的会话
  int? checkSameId({String? conversationId}) {
    List<ChatModel?> list = state.model.toList();

    /// 会话id列表
    var conversationList = [];
    for (var state in list) {
      conversationList.add(state?.xinMsg?.conversationId);
    }
    return conversationList
        .firstWhere((element) => element == 'conversationId');
  }

  /// 清除当前会话角标并跳转页面
  clearBar(index) {
    Provider.nickName = "";
    state.model[index].serverMeg?.count = 0;
    state.model[index].superXin?.markAllMessagesAsRead().then((value) {
      if (state.model[index].serverMeg?.index == 3) {
        pushGroupAction(index);
      } else {
        if (state.model[index].xinMsg?.from == 'admin') {
          pushSystemAction(index);
        } else {
          pushAction(index);
        }
      }
    });
    // EMClient.getInstance.chatManager.getUnreadMessageCount().then((value) {
    //   Brage().setIOSBrage(brage: value);
    //   EventBus.instance.commit(eventName:EventKeys.chatUpdateBadge,data: value);
    // });
  }

  /// 有消息变化 更新消息
  pushAction(int index) {
    Get.toNamed(PageRouteNames.messageChat, arguments: {
      'nickName': state.model[index].serverMeg?.nickName,
      'id': state.model[index].superXin!.id,
      'avatarUrl': state.model[index].serverMeg?.photoUrl,
    })?.then((value) {
      if (value != null) {
        dataUpdate(value);
      }
      state.model.refresh();
    });
  }

  /// 跳转到群聊
  pushGroupAction(int index) {
    Get.toNamed(PageRouteNames.meetGroupChat, arguments: {
      'id': state.model[index].superXin!.id,
      'owner': '${state.model[index].serverMeg!.owner}',
      'title':
          '${state.model[index].serverMeg?.nickName}(${state.model[index].serverMeg?.age})',
      'avatarUrl': state.model[index].serverMeg?.photoUrl,
    })?.then((value) {
      if (value != null) {
        dataUpdate(value);
      }
      state.model.refresh();
    });
  }

  pushSystemAction(int index) {
    Get.toNamed(PageRouteNames.systemMessageChat,
            arguments: state.model[index].superXin!.id)
        ?.then((value) {
      state.model.refresh();
    });
  }

  ///  替换消息
  dataUpdate(EMMessage message) {
    int index = state.model.indexWhere(
        (element) => element.xinMsg?.conversationId == message.conversationId);
    if (index != -1) {
      state.model[index].xinMsg = message;
      // state.model[index].serverMeg?.count = 0;
    }
  }
}
